package org.sky.axis2.soap;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.client.async.AxisCallback;
import org.apache.axis2.context.MessageContext;

public class SoapServiceClient {
	private static EndpointReference targetEPR = new EndpointReference(
			"http://localhost:8080/Axis2Service/services/SoapService");
	public static boolean finish = false;

	public static void orderRequest() {
		OMFactory factory = OMAbstractFactory.getOMFactory();
		OMNamespace omNs = factory.createOMNamespace(
				"http://soap.axis2.sky.org", "");
		OMElement issuer = factory.createOMElement("Issuer", omNs);
		OMElement serial = factory.createOMElement("Serial", omNs);
		OMElement revocationDate = factory.createOMElement("RevocationDate",
				omNs);
		issuer.setText("Wrox");
		serial.setText("1111111111ISBN");
		revocationDate.setText("2012-07-29");
		OMElement requestSoapMessage = factory.createOMElement("request", omNs);
		requestSoapMessage.addChild(issuer);
		requestSoapMessage.addChild(serial);
		requestSoapMessage.addChild(revocationDate);
		requestSoapMessage.build();
		Options options = new Options();
		options.setTo(targetEPR);
		ServiceClient sender = null;
		try {
			AxisCallback callback = new AxisCallback() {
				public void onMessage(MessageContext msgContext) {
					OMElement result = msgContext.getEnvelope().getBody()
							.getFirstElement();
					// System.out.println(msgContext.toString());
					// System.out.println(msgContext.getEnvelope().toString());
					System.out.println(msgContext.getEnvelope().getBody()
							.getFirstElement());
					finish = true;
				}

				public void onFault(MessageContext msgContext) {
					System.out.println(msgContext.getEnvelope().getBody()
							.getFault().toString());
				}

				public void onError(Exception e) {
				}

				public void onComplete() {
					System.out.println("Completed!!!");
				}
			};
			sender = new ServiceClient();
			sender.setOptions(options);
			System.out.println("-------Invoke the service---------");
			sender.sendReceiveNonBlocking(requestSoapMessage, callback);
			synchronized (callback) {
				if (!finish) {
					try {
						callback.wait(1000);
					} catch (Exception e) {
					}
				}
				if (!finish) {
					throw new AxisFault(
							"Server was shutdown as the async response take too long to complete");
				}
			}
		} catch (AxisFault e) {
			e.printStackTrace();
		} finally {
			if (sender != null)
				try {
					sender.cleanup();
				} catch (Exception e) {
				}
		}

	}

	public static void main(String[] args) {
		orderRequest();
	}
}